<template>
  <div class="mod-config" v-loading="loading">
    <el-collapse accordion>
      <el-collapse-item style="border: 1px solid #8c939d ">
        <template slot="title">
          <span class="span_title">项目基本信息</span>
        </template>
        <div class="span_text">
          <div><strong>项目编号：</strong>{{ projectInfo.projectNo }}</div>
          <div><strong>项目名称：</strong>{{ projectInfo.projectName }}</div>
          <div><strong>项目类型：</strong>{{ projectInfo.projectType }}</div>
          <div><strong>业务负责人：</strong>{{ projectInfo.contractBusiness }}</div>
          <div><strong>项目负责人：</strong>{{ projectInfo.projectCharge }}</div>
          <div><strong>项目跟单员：</strong>{{ projectInfo.projectBusiness }}</div>
          <div><strong>工作内容：</strong>{{ projectInfo.workNote }}</div>
          <div><strong>提交质检人员：</strong>{{ projectInfo.qualityUsername }}</div>
          <div style="display:flex;padding-bottom: 4px;"><strong>项目清单：</strong>
            <el-table :data="projectInfo.projectBillList" border>
              <el-table-column prop="billName" header-align="center" align="center" label="项目"></el-table-column>
              <el-table-column prop="spec" header-align="center" align="center" label="规格"></el-table-column>
              <el-table-column prop="num" header-align="center" align="center" label="数量"></el-table-column>
              <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <el-card class="box-card card_work">
      <div>作业工作量：{{ projectInfo.workLoad }}</div>
      <div>预计总产值：{{ projectInfo.projectOutput }}</div>
      <div style="color: #00b7ee">实际总产值：{{ totalOutPut }}</div>
    </el-card>

    <el-row :gutter="24" class="card_work">
      <el-col :span="7">
        <div class="card_work" style="color: #00b7ee">结算时间：
          <el-date-picker v-model="cutOffTime" type="month" value-format="yyyy-MM" placeholder="结算时间"
                          style="width: 150px;"></el-date-picker>
        </div>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <strong style="font-size: 13px;">项目类型：</strong>
            <el-select v-model="ptValue" multiple collapse-tags style="width: 75%;"
                       @change="projectTypeChangeHandler()">
              <el-option v-for="item in projectTypelist" :label="item.name" :key="item.id" :value="item.id"></el-option>
            </el-select>
          </div>
          <div class="left_work">
            <el-checkbox
              v-for="(workType, index) in leftData"
              :key="index"
              :label="workType.typeName"
              v-if="workType.isVisible && workType.listIndex == groupradio"
              v-model="workType.checked"
              @change="checkOutputVoInit"
              class="checkbox_class"
            ></el-checkbox>
          </div>
        </el-card>
      </el-col>
      <el-col :span="17">
        <!--作业组-->
        <el-divider class="group_divider" content-position="center"><i class="el-icon-set-up"></i><span>作业组</span>
        </el-divider>
        <el-radio-group v-model="groupradio" style="width: 100%">
          <div v-for="(groupOutput,index) in outPutGroupList" v-if="groupOutput.checked">
            <el-row style="margin-top: 5px;">
              <el-col :span="18">
                <el-card>
                  <div slot="header" class="clearfix">
                    <el-radio :label="groupOutput.groupId">
                      <span class="group_card">{{ groupOutput.groupName }}</span>
                      <span>(队长：{{ groupOutput.headMan }})</span>
                      <span v-if="groupOutput.headMan == projectInfo.projectCharge" style="color: red">(项目负责人)</span>
                    </el-radio>
                  </div>
                  <el-table :data="chooseRatio(groupOutput.checkOutputVoList)" border :header-cell-style="{background: 'cornflowerblue',color:'white'}">
                    <el-table-column prop="typeName" header-align="center" align="left" label="作业类型" width="150"></el-table-column>
                    <el-table-column prop="unit" header-align="center" align="center" label="产值单位" width="120"></el-table-column>
                    <el-table-column prop="unitOutput" header-align="center" align="center" label="产值单价"></el-table-column>
                    <el-table-column prop="projectRatio" header-align="center" align="center" label="难度系数" width="120">
                      <template slot-scope="scope">
                        <el-input type="number" :disabled="!scope.row.checked" v-model="scope.row.projectRatio" @change="checkOutputVoInit"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="workLoad" header-align="center" align="center" label="工作量" width="120">
                      <template slot-scope="scope">
                        <el-input type="number" :disabled="!scope.row.checked || scope.row.typeId == -99" v-model="scope.row.workLoad" min="0" @change="checkOutputVoInit"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="typeOutput" header-align="center" align="center" label="产值" width="100"></el-table-column>
                  </el-table>
                  <div span class="font_card">
                    <span>预计产值：{{ groupOutput.projectOutput }}</span>
                    <span>（预计占比：{{ groupOutput.outputRate }}%）。  </span>
                    <span>实际产值：{{ groupOutput.projectActuallyOutput }}。</span>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="6">
                <el-card>
                  <div slot="header" class="clearfix">
                    <span class="span_title">备注</span>
                  </div>
                  <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 10}"
                            v-model="remarkList[groupOutput.groupId]"></el-input>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-radio-group>
        <!--质检组-->
        <el-divider class="group_divider" content-position="center"><i class="el-icon-service"></i><span>质检组</span>
        </el-divider>
        <div style="float: right;border-bottom: 1px solid cornflowerblue;">
          <el-button icon="el-icon-plus" type="primary" @click="addQualityOutputHandle">添加</el-button>
        </div>
        <el-table :data="qualityOutputList" border :header-cell-style="{background: 'cornflowerblue',color:'white'}">
          <el-table-column prop="qualityUsername" header-align="center" align="left" label="质检人员" width="150">
            <template slot-scope="scope">
              <el-autocomplete v-model="scope.row.qualityUsername" :fetch-suggestions="queryNameSearch"
                               @select="((item)=>{handleNameSelect(item, scope.row.id)})" required="true"
                               style="width: 100%">
                <template slot-scope="{ item }">
                  <div class="name">{{ item.username }}</div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column prop="outsideCheck" header-align="center" align="center" label="是否外检" width="180">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.outsideCheck">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column prop="outputRatio" header-align="center" align="center" label="产值占比(%)" width="140">
            <template slot-scope="scope">
              <el-input v-model="scope.row.outputRatio" type="number" size="small" @input="changQOutputHandle(1)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="projectActuallyOutput" header-align="center" align="center" label="产值" width="160">
            <template slot-scope="scope">
              <el-input v-model="scope.row.projectActuallyOutput" type="number" size="small" @input="changQOutputHandle(2)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="outputRemark" header-align="center" align="center" label="备注">
            <template slot-scope="scope">
              <el-input v-model="scope.row.outputRemark"></el-input>
            </template>
          </el-table-column>
          <el-table-column header-align="center" align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" size="small"
                         @click="deleteQualityItem(scope.row.id)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div class="bottom_btn">
      <el-button type="warning" size="large" @click="goBack">返回</el-button>
      <el-button type="primary" size="large" @click="saveForm">提交</el-button>
    </div>
  </div>
</template>

<script>
import {closeTab} from '@/utils/tabs'
import {getUUID, stringIsNull} from '@/utils'

export default {
  data () {
    return {
      getArgsPageIndex: this.$route.query.pageIndex,
      getArgsPageSize: this.$route.query.pageSize,
      loading: true,
      groupradio: 0,
      totalOutPut: 0, // 实际总产值
      leftData: [], // 左侧数据显示
      projectNo: '',
      projectInfo: '',
      projectTypelist: [],   // 项目类型列表
      ptValue: [],
      workTypelist: [],   // 工作类型列表
      outPutGroupList: [],
      qualityNoteValue: '',
      cutOffTime: '',
      remarkList: [],  // 预算备注列表
      qualityOutputList: [],  // 质检产值列表
      qualityMenList: []    // 质检人员列表
    }
  },
  computed: {
    argsPageIndex: {
      get () {
        return this.$store.state.paramsutil.argsPageIndex
      },
      set (val) {
        this.$store.commit('paramsutil/updateargsPageIndex', val)
      }
    },
    argsPageSize: {
      get () {
        return this.$store.state.paramsutil.argsPageSize
      },
      set (val) {
        this.$store.commit('paramsutil/updateargsPageSize', val)
      }
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    init () {
      this.projectNo = this.$route.query.projectNo
      this.getQualitMenList().then(list => {
        this.qualityMenList = list
      })
      this.getQualityOutputList()
      this.getInfoByProjectNo(this.projectNo).then(data => {
        this.projectInfo = data
        this.getCutoffTime()
        this.getProjectTypelist().then(success => {
          this.getWorkTypelist().then(success => {
            let ptType = this.projectInfo.projectType.split(',')
            console.log(ptType)
            for (let pt of this.projectTypelist) {
              for (let type of ptType) {
                if (pt.name === type) {
                  this.ptValue.push(pt.id)
                }
              }
            }
            this.workTypeInit()
            this.getOutPutGroupList(this.projectNo).then(success => {
              for (let e of this.outPutGroupList) {
                // 默认选中第一个组
                if (e.checked) {
                  this.groupradio = e.groupId
                  break
                }
              }
              // 初始化备注
              let remarkList = []
              for (let e of this.outPutGroupList) {
                if (e.checked) {
                  remarkList[e.groupId] = ''
                }
              }
              // 各队产值备注 赋值
              this.getRemarkList().then(list => {
                for (let key in remarkList) {
                  for (let group of list) {
                    if (group.groupId === parseInt(key)) {
                      remarkList[key] = group.remark
                    }
                  }
                }
                this.remarkList = remarkList
              })
              this.checkOutputVoInit()
              this.loading = false
            })
          })
        })
      })
    },
    // 质检产值列表
    getQualityOutputList () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/qualityoutput/list`),
          method: 'get',
          params: this.$http.adornParams({
            projectNo: this.projectNo
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.qualityOutputList = data.list
            console.log(data.list)
            resolve(data.list)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 质检员查找项
    queryNameSearch (queryString, cb) {
      var list = this.qualityMenList
      var results = queryString ? list.filter(this.createFilter(queryString)) : list
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter (queryString) {
      return (restaurant) => {
        return (restaurant.username.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleNameSelect (item, id) {
      this.qualityOutputList.find(dat => dat.id === id).qualityUsername = item.username
      this.qualityOutputList.find(dat => dat.id === id).qualityUseraccount = item.useraccount
      console.log(this.qualityOutputList)
    },
    changQOutputHandle (type) {
      switch (type) {
        // 产值占比
        case 1:
          this.qualityOutputList.forEach((item, index) => {
            item.projectActuallyOutput = (parseFloat(item.outputRatio) * parseFloat(this.totalOutPut) / 100).toFixed(2)
          })
          break
        // 产值
        case 2:
          this.qualityOutputList.forEach((item, index) => {
            item.outputRatio = (parseFloat(item.projectActuallyOutput) / parseFloat(this.totalOutPut) * 100).toFixed(2)
          })
          break
        default:
          break
      }
    },
    // 添加质检产值项
    addQualityOutputHandle () {
      let qulityItem = {
        id: getUUID(),
        qualityUsername: '',
        projectNo: this.projectNo,
        outsideCheck: false,
        outputRatio: 0,
        projectActuallyOutput: 0,
        outputRemark: ''
      }
      this.qualityOutputList.push(qulityItem)
    },
    // 删除质检项
    deleteQualityItem (id) {
      let qList = []
      this.qualityOutputList.forEach((data, index) => {
        if (data.id !== id) {
          qList.push(data)
        }
      })
      this.qualityOutputList = qList
    },
    // 工作类型可见或不可见
    workTypeInit () {
      for (let workType of this.workTypelist) {
        workType.isVisible = false
        // 工作类型 不属于 任意项目则设为 可见
        if (workType.projectTypeIdList.length === 0) {
          workType.isVisible = true
        } else {
          for (let ptypeId of workType.projectTypeIdList) {
            for (let ptvalue of this.ptValue) {
              if (ptvalue === ptypeId) workType.isVisible = true
            }
          }
        }
      }
    },
    // 根据工作类型可见不可见 来显示右侧工作组工作类型数据
    checkOutputVoInit () {
      this.leftData = []
      this.totalOutPut = 0
      this.outPutGroupList.forEach((e, index) => {
        if (e.checked) {
          e.projectActuallyOutput = 0
          let workloadAll = 0
          e.checkOutputVoList.forEach(ele => {
            // 各组工作类型产值
            ele.typeOutput = 0
            ele.typeOutput = parseFloat((ele.projectRatio * ele.unitOutput * ele.workLoad).toFixed(2))

            if (ele.checked) {
              e.projectActuallyOutput = parseFloat((e.projectActuallyOutput + ele.typeOutput).toFixed(2))
              // 提取产值
              if (ele.typeId === -99) {
                ele.workLoad = workloadAll
              } else {
                workloadAll = (parseFloat(workloadAll) + parseFloat(ele.workLoad)).toFixed(2)
              }
            }
            ele.isVisible = false
            this.workTypelist.forEach((work, index) => {
              if (work.id === ele.typeId && work.isVisible) ele.isVisible = true
            })
            ele.listIndex = e.groupId
          })
          this.leftData = this.leftData.concat(e.checkOutputVoList)
          this.totalOutPut = parseFloat((this.totalOutPut + e.projectActuallyOutput).toFixed(2))
        }
      })
      this.changQOutputHandle(1)
      // console.log(this.leftData)
    },
    // 获取工作组的产值核算
    getOutPutGroupList (projectNo) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/checkoutput/getOutPutGroup`),
          method: 'get',
          params: this.$http.adornParams({
            projectNo: projectNo
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.outPutGroupList = data.list
            resolve(data.list)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 获取结算时间
    getCutoffTime () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/quality/getInfo`),
          method: 'get',
          params: this.$http.adornParams({
            'projectNo': this.projectNo
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.cutOffTime = data.checkQuality.cutOffTime
            this.projectInfo.qualityUsername = data.checkQuality.qualityUsername
            resolve(data.checkQuality)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 获取项目基本信息
    getInfoByProjectNo (projectNo) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/projectInfo/info/${projectNo}`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.projectInfo)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 获取列表
    getQualitMenList () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/sys/user/getUserList/10'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.list)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 获取项目类型列表
    getProjectTypelist () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/set/projecttype/getProjectTypelist`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.projectTypelist = []
            this.projectTypelist.push({id: 0, name: '全部'})
            // console.log(this.projectTypelist)
            for (let item of data.list) {
              this.projectTypelist.push({id: item.id, name: item.name})
            }
            resolve(data.projectTypelist)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 获取工作类型列表
    getWorkTypelist () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/set/worktype/getList`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.workTypelist = data.list
            resolve(data.workTypelist)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 根据项目编号获取产值备注列表
    getRemarkList () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/outputremark/list`),
          method: 'get',
          params: this.$http.adornParams({
            'projectNo': this.projectNo
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.list)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 提交结算时间
    postCutoffTimeToApi () {
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl(`/project/quality/cutOffTimesave`),
          method: 'post',
          data: this.$http.adornData({
            'projectNo': this.projectNo,
            'cutOffTime': this.cutOffTime
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    // 保存产值核算
    postOutputToApi () {
      this.loading = true
      this.$http({
        url: this.$http.adornUrl(`/project/checkoutput/save`),
        method: 'post',
        data: this.$http.adornData({
          'projectNo': this.projectNo,
          'pgroupList': this.outPutGroupList,
          'projectActuallyOutput': this.totalOutPut
        })
      }).then(({data}) => {
        this.loading = false
        if (data && data.code === 0) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500
          })
          this.visible = false
          this.$emit('refreshDataList')
          this.goBack()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 保存备注
    putRemarkToApi () {
      return new Promise((resolve, reject) => {
        let markList = []
        for (let key in this.remarkList) {
          if (!stringIsNull(this.remarkList[key])) {
            markList.push({
              groupId: key,
              projectNo: this.projectNo,
              remark: this.remarkList[key]
            })
          }
        }
        this.$http({
          url: this.$http.adornUrl(`/project/outputremark/saveList`),
          method: 'post',
          data: this.$http.adornData({
            'projectNo': this.projectNo,
            'outputRemarkList': markList
          })
        }).then(({data}) => {
          if (data && data.code === 0) {

          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    // 保存质检核算
    putQualityOutputToApi () {
      return new Promise((resolve, reject) => {
        this.qualityOutputList.forEach((item, index) => {
          item.id = null
        })
        this.$http({
          url: this.$http.adornUrl(`/project/qualityoutput/saveList`),
          method: 'post',
          data: this.$http.adornData({
            'projectNo': this.projectNo,
            'qOutputList': this.qualityOutputList
          })
        }).then(({data}) => {
          if (data && data.code === 0) {

          } else {
            this.$message.error(data.msg)
          }
        })
      })
    },
    saveForm () {
      this.postCutoffTimeToApi().then(success => {
        this.postOutputToApi()
        this.putRemarkToApi()
        this.putQualityOutputToApi()
      })
    },
    // 项目类型改变
    projectTypeChangeHandler () {
      for (let ptvalue of this.ptValue) {
        // 选择全部项目时
        if (ptvalue === 0) {
          this.ptValue = []
          for (let pw of this.projectTypelist) if (pw.id !== 0) this.ptValue.push(pw.id)
          break
        }
      }
      this.workTypeInit()
      this.checkOutputVoInit()
    },
    // 保留小数点后两位的过滤器，尾数不四舍五入
    numFilter (value) {
      // 截取当前数据到小数点后三位
      let tempVal = parseFloat(value).toFixed(3)
      let realVal = tempVal.substring(0, tempVal.length - 1)
      return realVal
    },
    // 工作类型在表格勾选显示
    chooseRatio (params) {
      //  console.log(params)
      let temp = []
      params.forEach(e => {
        if (e.checked) {
          e.typeOut = this.numFilter(
            e.workLoad * e.projectRatio * e.typeOutput
          )
          if (e.projectRatio == null || e.workLoad == null) {
            e.projectRatio = 1
            e.workLoad = 0
          }
          temp.push(e)
        }
      })
      return temp
    },
    // 返回
    goBack () {
      closeTab('project-editoutput')
      this.argsPageSize = this.getArgsPageSize
      this.argsPageIndex = this.getArgsPageIndex
      this.$router.push('project-project')
    }
  },
  watch: {
    '$route': function (to, from) {
      this.projectNo = to.query['projectNo']
      // 执行数据更新查询
      if (to.name === 'project-editoutput') {
        this.init()
      } else {
        closeTab('project-editoutput')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.form_class {
  margin-top: 20px;

}

.span_title {
  font-size: 18px;
  font-weight: 700;
}

.span_text {
  background-color: #f0f0f0;
  font-size: 15px;
}

.bottom_btn {
  margin: 20px;
  width: 100%;
  text-align: center;
}

.card_work {
  margin-top: 20px;
  font-size: 16px;
  margin-bottom: 10px;
}

.left_work {
  border: 1px solid #6f7180;
  text-align: left;
  overflow-x: hidden;
  overflow-y: auto;
  height: 400px;
}

.checkbox_class {
  width: 95%;
  margin-left: 0;
}

.group_card {
  font-weight: 700;
  font-size: 17px;
}

.font_card {
  font-weight: 700;
  font-size: 15px;
  color: cornflowerblue;
}

.card_header {
  margin-top: 18px;
}

.card_header .header_span {
  font-weight: 700;
  font-size: 14pt;
}

.group_divider {
  i {
    font-size: 11pt;
    color: #006F94;
  }

  span {
    font-weight: 700;
    font-size: 12pt;
    color: #006F94;
    //color: ;
  }
}
</style>
